package com.quanyan.ic.parkingLot.http.service.impl;

import com.google.gson.Gson;
import com.quanyan.ic.common.utils.HttpClientUtils;
import com.quanyan.ic.parkingLot.http.service.BaseService;
import com.quanyan.ic.parkingLot.model.HikApiResponse;
import com.quanyan.ic.parkingLot.utils.HikTokenGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by zhang on 17/8/22.
 */
@Service
public class BaseServiceImpl implements BaseService {
    private final static Logger logger = LoggerFactory.getLogger(BaseServiceImpl.class);
    @Value("${hik.parking.appkey}")
    private String hikParkingAppkey;
    @Value("${hik.parking.secret}")
    private String hikParkingSecret;
    @Value("${hik.parking.address}")
    private String address;
    @Value("${hik.parking.deviceControl}")
    private String deviceControlPath;
    /**
     * 道闸控制
     * @param roadwaySyscode 车道信息
     * @param command 控闸命令( 开闸:0 关闸:1 常开:2)
     * @return
     */
    @Override
    public HikApiResponse deviceControl(String roadwaySyscode,String command) {
        StringBuilder param = new StringBuilder();
        param
                .append("?")
                .append("roadwaySyscode=")
                .append(roadwaySyscode)
                .append("&command=")
                .append(command)
                .append("&appkey=")
                .append(hikParkingAppkey)
                .append("&time=")
                .append(System.currentTimeMillis());

        String token = HikTokenGenerator.generatorGetToken(address, deviceControlPath, param.toString(), hikParkingAppkey, hikParkingSecret);
        StringBuilder url = new StringBuilder();
        url
                .append(address)
                .append(deviceControlPath)
                .append(param)
                .append("&token=")
                .append(token);
        HikApiResponse response;
        try {
            String result = HttpClientUtils.get(url.toString());
            response = new Gson().fromJson(result, HikApiResponse.class);
        } catch (Exception e) {
            logger.error("道闸控制失败：失败车道信息：【{}】；失败的命令：【{}】；失败时间：【{}】；异常信息：{}", roadwaySyscode,command,new Date(),e);
            response = new HikApiResponse();
            response.setErrorMessage("系统异常");
        }

        return response;
    }
}
